package demo.db.elasticSearch.transport;

import java.net.InetAddress;
import java.net.UnknownHostException;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

/**
 * ES提供了两个JAVA REST client 版本
 * <li>Java Low Level REST Client: 低级别的REST客户端，通过http与集群交互，用户需自己编组请求JSON串，及解析响应JSON串。兼容所有ES版本。
 * <li>Java High Level REST Client:
 * 高级别的REST客户端，基于低级别的REST客户端，增加了编组请求JSON串、解析响应JSON串等相关api。使用的版本需要保持和ES服务端的版本一致，否则会有版本问题。
 * 
 * 
 * 
 * @author hanjy
 *
 */
public class InitDemo {

    private TransportClient transportClient;

    @Value("${es.connection.host}")
    private static String hosts = "172.17.16.165:9300";

    @Value("${es.cluster.name}")
    private static String clusterName = "my-es";

    @Value("${es.conflict.retry.times}")
    private Integer retry;

    public static final int FROM = 0;
    public static final int SIZE = 5000;

    private static Logger logger = LoggerFactory.getLogger(InitDemo.class);

    public static void main(String[] args) {
        try (TransportClient client = init(clusterName, hosts)) {

        } catch (Exception e) {
            logger.error("", e);
        }
    }

    public static TransportClient getClient() throws UnknownHostException {
        return init(clusterName, hosts);
    }

    /**
     * Init Client setting 可用参数说明：
     * 
     * <li>cluster.name： 指定集群的名字，如果集群的名字不是默认的elasticsearch，需指定。
     * <li>client.transport.sniff： 设置为true,将自动嗅探整个集群，自动加入集群的节点到连接列表中。
     * <li>client.transport.ignore_cluster_name： Set to true to ignore cluster name validation of connected nodes.
     * (since 0.19.4)
     * <li>client.transport.ping_timeout： The time to wait for a ping response from a node. Defaults to 5s.
     * <li>client.transport.nodes_sampler_interval： How often to sample / ping the nodes listed and connected. Defaults
     * to 5s.
     * 
     * @param clusterName
     *            默认集群名为elasticsearch，如果集群名称和指定的不一致则在使用节点资源时会报错。
     * @param hosts
     * @return
     * @throws UnknownHostException
     */
    public static TransportClient init(String clusterName, String hosts) throws UnknownHostException {
        System.setProperty("es.set.netty.runtime.available.processors", "false");
        // 连接集群的设置
        Settings settings = Settings.builder().put("cluster.name", clusterName).build();
        TransportClient transportClient = new PreBuiltTransportClient(settings);
        String[] hostArray = hosts.split(",");

        for (String host : hostArray) {
            String[] param = host.split(":");
            transportClient.addTransportAddress(
                    new TransportAddress(InetAddress.getByName(param[0]), Integer.parseInt(param[1])));
        }
        return transportClient;
    }

}